import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:share_extend/share_extend.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:math' as math;

class DynamicInfoWidget extends StatefulWidget {
  final int id;
  DynamicInfoWidget({required this.id});

  @override
  _DynamicInfoWidget createState() => _DynamicInfoWidget(id: id);
}

class _DynamicInfoWidget extends State<DynamicInfoWidget>
    with TickerProviderStateMixin {
  int id;
  late Future<dynamic> _function;
  late DynamicDataEntity _dynamicDataEntity;
  ScrollController? _scrollController;
  double _opacity = 0.0;
  bool changeDown = true;
  bool changeUp = false;
  String titleData = '动态详情';

  _DynamicInfoWidget({required this.id});

  @override
  void initState() {
    super.initState();
    _function = future();
  }

  @override
  void dispose() {
    _scrollController!.dispose();
    super.dispose();
  }

  future() async {
    await HomeService.setRecentVisit(params: {
      'recentVisit_Type':1,
      'user_Id':SPreferences().getInt('user_Id'),
      'thing_Id':id
    });
    await getInfoData();
  }

  Future<void> getInfoData() async {
    DynamicDataEntity res = await DynamicService.dynamicInfo(params: {
      'dynamic_Id': id,
      'user_Id': SPreferences().getInt('user_Id')
    });
    _dynamicDataEntity = res;
    listenTitle();
  }
  /// 分享给好友
  shareImg() async {
    ShareExtend.share(
      "[有人@你]\n有人发了条动态\n\n${_dynamicDataEntity.dynamicIntroduce}\n\n动态访问地址：http://192.168.31.202:4001/app/thinking.apk",
      "text",
      sharePanelTitle: "thinking",
    );
  }



  void listenTitle() {
    _scrollController = ScrollController();
    _scrollController!.addListener(() {
      if (_scrollController!.offset > 65 && changeDown) {
        setState(() {
          titleData = _dynamicDataEntity.dynamicUser!.userNickName!;
          _opacity = 1.0;
          changeDown = false;
          changeUp = true;
        });
      }
      if (_scrollController!.offset < 65 && changeUp) {
        setState(() {
          _opacity = 0.0;
          changeDown = true;
          titleData = '动态详情';
          changeUp = false;
        });
      }
    });
  }

  Future<dynamic> showModalBottom() {
    return showModalBottomSheet(
        context: context,
        elevation: 10,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        builder: (BuildContext context) {
          return Container(
            height: Screen.setHeight(180),
            padding: EdgeInsets.only(top: Screen.setHeight(10)),
            child: Container(
              height: 50,
              child: Column(
                children: [
                  TextButton(
                    style: ButtonStyle(
                      overlayColor: MaterialStateProperty.all(
                          ColorConfig.LineColor
                      ),
                    ),
                    child: Center(
                      child: Text(
                        _dynamicDataEntity.dynamicIsCollection!?'取消收藏':'收藏',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.black
                        ),
                      ),
                    ),
                    onPressed: () async {

                      Modular.to.pop();
                      await changeCollection();
                    },
                  ),
                  Line(height: 1,width: Screen.setWidth(Screen.width(context)-40),),
                  TextButton(
                    style: ButtonStyle(
                      overlayColor: MaterialStateProperty.all(
                          ColorConfig.LineColor
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '分享',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.black
                        ),
                      ),
                    ),
                    onPressed: () async {

                      await shareImg();
                      Modular.to.pop();
                    },
                  ),
                  Line(height: 1,width: Screen.setWidth(Screen.width(context)-40),),
                  TextButton(
                    style: ButtonStyle(
                      overlayColor: MaterialStateProperty.all(
                          ColorConfig.LineColor
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '举报',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.black
                        ),
                      ),
                    ),
                    onPressed: () {

                      Modular.to.pop();
                    },
                  ),
                  Line(height: 1,width: Screen.setWidth(Screen.width(context)-40),),
                ],
              ),
            ),
          );
        }
    );
  }

  Future<void> changeCollection()async{

    _dynamicDataEntity.setDynamicIsCollection = !_dynamicDataEntity.dynamicIsCollection!;

    await DynamicService.changeDynamicCollection(params: {
      'user_Id':SPreferences().getInt('user_Id'),
      'dynamic_Id':_dynamicDataEntity.dynamicId,
      'isCollection':_dynamicDataEntity.dynamicIsCollection
    });
   if(_dynamicDataEntity.dynamicIsCollection!) BotToast.showText(text: '收藏成功');
  }

  /// 保存图片到相册
  saveGallery(String url) async {
    var response = await PublicService.downImage(url: Config.apiUrl['BasePhotoUrl']+url, params: {});
    String fileName = Tool.randomBit();
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response),
        quality: 100,
        name: fileName
    );
    result['isSuccess']
        ? BotToast.showText( text: '图片存储在 ${result['filePath']}')
        : BotToast.showText( text:"保存失败");
  }

    Widget title() {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(
            top: Screen.setHeight(Config.top),
          ),
          height: Screen.setHeight(85),
          width: Screen.width(context),
          child: ListTile(
            minVerticalPadding: 0,
            contentPadding: EdgeInsets.all(0),
            leading: IconButton(
              onPressed: () {
                Modular.to.pop();
              },
              icon: Icon(
                Icons.arrow_back,
                color: ColorConfig.BlackObsBackColor,
                size: 20,
              ),
            ),
            trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Visibility(
                      child: AnimatedOpacity(
                opacity: _opacity,
    duration: Duration(milliseconds: 350),
    child: FollowButton(
                          userData: _dynamicDataEntity.dynamicUser!)),
                      visible: SPreferences().getInt('user_Id') !=
                          _dynamicDataEntity.dynamicUser!.userId),
                  SizedBox(
                    width: 5,
                  ),
                  GestureDetector(
                    onTap: () async {
                      await showModalBottom();
                    },
                    child: Transform.rotate(
                      //旋转90度
                      angle: math.pi / 2,
                      child: Icon(Icons.more_horiz,color: ColorConfig.BlackBackColor,),
                    ),
                  ),
                  SizedBox(
                    width: 15,
              ),
                    ]
            )
          ),
        ),
        Container(
          width: Screen.width(context),
          margin: EdgeInsets.only(
            top: Screen.setHeight(Config.top),
          ),
         child:   Center(
                child: Text(
                  titleData.length>5?titleData.substring(0,5)+'...':titleData,
                  style: TextStyle(fontSize: 16),
                ),
              ),

        )
      ],
    );
  }

  Panel dynamicContentTopListTitle() {
    return Panel(
      top: 10,
      bottom: 10,
      left: 0,
      right: 0,
      child: ListTile(
        leading: ClipRRect(
          borderRadius: BorderRadius.circular(30),
          child: ClipOval(
            child: Image.network(
              _dynamicDataEntity.dynamicUser!.userHeadImg!,
              height: Screen.setWidth(48),
              width: Screen.setWidth(48),
              fit: BoxFit.cover,
            ),
          ),
        ),
        title: Text(
          _dynamicDataEntity.dynamicUser!.userNickName != '暂无'
              ? _dynamicDataEntity.dynamicUser!.userNickName.toString()
              : _dynamicDataEntity.dynamicUser!.userPhone.toString(),
          style: TextStyle(
              color: ColorConfig.ThemeColor, fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          Tool.dateAndTimeToString(
            Tool.timeToStamp(_dynamicDataEntity.dynamicTime!),
            formart: {"y-m": "-", "m-d": "-", "h-m": ":"},
          ),
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ),
        trailing: Visibility(
            child: FollowButton(userData: _dynamicDataEntity.dynamicUser!),
            visible: SPreferences().getInt('user_Id') !=
                _dynamicDataEntity.dynamicUser!.userId),
        minVerticalPadding: 0,
      ),
    );
  }

  Panel dynamicContentBottomListTitle() {
    return Panel(
        top: 10,
        bottom: 10,
        left: 0,
        right: 0,
        child: DynamicData(
          dynamicData: _dynamicDataEntity,
          onShare: () {},
          onLike: (bool isLike) async {
            await DynamicService.changeDynamicLike(params: {
              'user_Id': SPreferences().getInt('user_Id'),
              'dynamic_Id': _dynamicDataEntity.dynamicId,
              'isLike': isLike
            });
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _function,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return snapshot.connectionState == ConnectionState.done
            ? Scaffold(
                appBar: PreferredSize(
                  preferredSize: Size.fromHeight(55),
                  child: title(),
                ),
                body: Container(
                  child: MediaQuery.removePadding(
                    context: context,
                    child: ListView(
                      controller: _scrollController,
                      physics: BouncingScrollPhysics(),
                      shrinkWrap: true,
                      children: [
                        dynamicContentTopListTitle(),
                        Panel(
                            top: 0,
                            child:RichText(
                              textAlign: TextAlign.left,
                              text: TextSpan(children: <InlineSpan>[
                                TextSpan(
                                    children: _dynamicDataEntity.dynamicTagList != null
                                        ? _dynamicDataEntity.dynamicTagList!
                                        .map((e) => TextSpan(
                                        text: '#' + e + ' ',
                                        style: TextStyle(
                                            color: Colors.lightBlue,
                                            fontStyle: FontStyle.italic,
                                            fontSize: 14)))
                                        .toList()
                                        : null),
                                TextSpan(
                                    text: _dynamicDataEntity.dynamicIntroduce,
                                    style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.black87,
                                        overflow: TextOverflow.ellipsis))
                              ]),
                            )),
                        Column(
                          children: _dynamicDataEntity
                              .dynamicInfoEntity!.dynamicInfoImgList!
                              .asMap()
                              .keys
                              .map((e) => Panel(
                                      child: GestureDetector(
                                    onLongPress: () async {
                                      await showDialog(
                                          context: context,
                                          builder: (context) {
                                        return SimpleDialog(
                                          titlePadding: EdgeInsets.all(15),
                                          contentPadding: EdgeInsets.all(15),
                                          title: Container(
                                            alignment: Alignment.centerLeft,
                                            child: Row(
                                              children: [
                                                Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                                                SizedBox(width: 5,),
                                                Text("请选择操作",style: TextStyle(fontSize: 17),)
                                              ],
                                            ),
                                          ),
                                          children: <Widget>[
                                            TextButton(
                                                child: Text("保存到相册",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                                onPressed: () async {
                                                  Navigator.of(context).pop();
                                                 await saveGallery(_dynamicDataEntity
                                                     .dynamicInfoEntity!.dynamicInfoImgList![e]);
                                                }
                                            ),

                                          ],
                                        );
                                      }
                                      );
                                    },
                                    onTap: () {
                                      ImagePickers.previewImages(
                                          _dynamicDataEntity.dynamicInfoEntity!
                                              .dynamicInfoImgList!
                                              .map((e) {
                                            return (Config.apiUrl[
                                                        'BasePhotoUrl'] +
                                                    e)
                                                .toString();
                                          }).toList(),
                                          e);
                                    },
                                    child: ClipRRect(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(10)),
                                      child: Image(
                                        filterQuality: FilterQuality.high,
                                        image: NetworkImage(
                                            Config.apiUrl['BasePhotoUrl'] +
                                                _dynamicDataEntity
                                                    .dynamicInfoEntity!
                                                    .dynamicInfoImgList![e]),
                                        width: Screen.width(context),
                                      ),
                                    ),
                                  )))
                              .toList(),
                        ),
                        dynamicContentBottomListTitle()
                      ],
                    ),
                    removeLeft: true,
                    removeTop: true,
                  ),
                ),
              )
            : Scaffold(
                body: Loading(),
              );
      },
    );
  }
}
